package ru.autofan.logic;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ru.autofan.logic.dao.DomainFactory;

public class EntityPageFetcher {

	public static final Long ITEMS_BY_PAGE = 10L;

	private DaoSupporter daoSupporter;

	private DomainFactory domainFactory;

	public EntityPageFetcher() {

	}

	public EntityPageFetcher(DaoSupporter daoSupporter,
			DomainFactory domainFactory) {
		this.daoSupporter = daoSupporter;
		this.domainFactory = domainFactory;
	}

	public <ENTITY, FORM, FACTORY extends WrapEntityFactory<ENTITY, FORM>> List<FORM> fetch(
			Class<FACTORY> factoryClass, Class<ENTITY> entityClass,
			Class<FORM> formClass, Long page, String field)
			throws InstantiationException, IllegalAccessException {
		if (page == null) {
			page = Long.valueOf(1);
		}
		Iterator<Long> iterator = getCarIterator(entityClass, field);
		List<FORM> result = new ArrayList<FORM>();
		int selectedIndex = 1;
		while (iterator.hasNext()) {
			Long id = iterator.next();
			if (selectedIndex > page * ITEMS_BY_PAGE) {
				break;
			}
			if (selectedIndex > (page - 1) * ITEMS_BY_PAGE
					&& selectedIndex <= page * ITEMS_BY_PAGE) {
				ENTITY entity = this.domainFactory.get(entityClass, id);
				FACTORY factory = factoryClass.newInstance();
				FORM form = factory.wrap(entity);
				result.add(form);
			}
			selectedIndex++;
		}
	
		return result;
	}

	private Iterator<Long> getCarIterator(Class entity, String field) {
		String query = "select id from {0} order by {1}";
		query = MessageFormat.format(query, new Object[] {
				entity.getSimpleName(), field });
		
		return this.daoSupporter.getList(Long.class, query).iterator();
	}

	public <E> Long getEntityPages(Class<E> entityClass) {
		String query = "select count(id) from {0}";
		query = MessageFormat.format(query, new Object[] { entityClass
				.getSimpleName() });
		Number size = daoSupporter.getUniqueObject(Long.class, query);
		
		return size.longValue() / ITEMS_BY_PAGE
				+ (size.longValue() % 10L == 0L ? 0L : 1L);
	}

}
